<?php
require_once 'init_app.php';

set_time_limit(0); 

$mailboxes = ORM::factory('mailbox')
                ->find_all()
                ->as_array();     
foreach ($mailboxes as $mailbox) {
    $mailbox = ORM::factory('mailbox', $mailbox->id);   // Актуализируем
    if ($mailbox->is_processing) {
        continue;    
    }
    
    if (!$mailbox->mailbox_redirect) {
        continue;    
    }
    
    $mailbox->is_processing = 1;
    $mailbox->save();
    
    $company = ORM::factory('company', $mailbox->company_id);
    $company->set_as_current();
    
    $attachments_dir = APPPATH.'../media/uploads/attachments/'.$mailbox->id;
    if (!is_dir($attachments_dir)) {
        $old = umask(0);
        mkdir($attachments_dir, 0777);
        umask($old);   
    }
    try {
        //$imapmailbox = new Library_ImapMailbox('{109.120.184.13:143}INBOX', $mailbox->mailbox_redirect, $mailbox->clean_password, $attachments_dir, 'utf-8'); 
        $imapmailbox = new Library_ImapMailbox('{127.0.0.1:143}INBOX', $mailbox->mailbox_redirect, $mailbox->clean_password, $attachments_dir, 'utf-8');
        $messages = $imapmailbox->searchMailBox('ALL');
        foreach ($messages as $id) {
            if ($id <= $mailbox->current_mail_id) {
                continue;    
            }
            echo '#'.$id."\n";  
            
            $message = $imapmailbox->getMail($id);
            
            $email         = $message->fromAddress;
            $client_name   = $message->fromName;

            $subject       = $message->subject;
            $isset_re      = false;
            if (strpos($subject, 'RE') === 0) {
                $isset_re = true;
                $subject  = trim(substr($subject, strpos($subject, ':') + 1));  
            }
            if (strpos($subject, 'Re') === 0) {
                $isset_re = true;
                $subject  = trim(substr($subject, strpos($subject, ':') + 1));     
            }
            
            $date          = strtotime($message->date);
            
            $text          = $message->textHtml;
            if (!$text) {
                $text      = nl2br($message->textPlain);  
            } 
            
            $attachments = $message->getAttachments();
            
            try {
                //write_log($mailbox->email." - ".$id." - trying select existing ticket");
                $ticket = ORM::factory('ticket')->get_ticket_by_email_and_subject($mailbox, $email, $subject);
                // вставка
                if ($isset_re && $ticket->loaded()) {    // ответ
                    //write_log($mailbox->email." - ".$id." - trying adding new reply");
                    $reply = ORM::factory('reply')->add_reply($ticket, $text, $client_name, $email, $date, $attachments);
                    //write_log($mailbox->email." - ".$id." - ready adding new reply");      
                } else {            // новый тикет
                    //write_log($mailbox->email." - ".$id." - trying adding new ticket");
                    $ticket = ORM::factory('ticket')->add_ticket($mailbox, Model_Ticket::TYPE_EMAIL, $client_name, $email, null, $subject, $text, Model_Ticket::STATUS_ACTIVE, 0, $date, $attachments);     
                    //write_log($mailbox->email." - ".$id." - ready adding new ticket");
                }
                
                // обновление current_mail_id
                //write_log($mailbox->email." - ".$id." - trying update current mail id");
                $mailbox->current_mail_id = $id;
                $mailbox->save();
                //write_log($mailbox->email." - ".$id." - ready update current mail id");  
            } catch (Exception $e) {
                // TODO разобраться, не должно быть такого
                if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
                    continue;    
                }
                throw $e;
            }
            
            /*echo '<pre>';
            print_r($message);
            die();  */
        }         
        
        // try to connect
        /*$inbox = imap_open('{109.120.184.13:143}INBOX', $mailbox->mailbox_redirect, $mailbox->clean_password) or die('Cannot connect: ' . imap_last_error());
        // grab emails
        $emails = imap_search($inbox, 'ALL');
        
        print_r($emails);
        die();

        // if emails are returned, cycle through each...
        if ($emails) {
            // for every email...
            foreach($emails as $id) {
                echo '#'.$id."\n";
                if ($id <= $mailbox->current_mail_id) {
                    continue;    
                }
            
                // get information specific to this email/
                $structure = imap_fetchstructure($inbox, $id);
                $overview  = imap_fetch_overview($inbox, $id, 0);
                
                $from          = imap_utf8($overview[0]->from);
                $email         = Model_Main::cut_str('<', '>', $from);
                $client_name   = trim($from);

                // TODO Re
                $subject       = imap_utf8(mb_decode_mimeheader($overview[0]->subject));
                $isset_re      = false;
                if (strstr($subject, 'Re:') !== false) {
                    $isset_re = true;
                    $subject  = trim(str_replace('Re:', '', $subject));     
                }
                
                $date          = imap_utf8($overview[0]->date);
                $date          = strtotime($date);
                
                $message   = get_part($inbox, $id, "TEXT/HTML");
                if (!$message) {
                    $message = get_part($inbox, $id, "TEXT/PLAIN"); 
                    $message = nl2br($message);  
                } 
                
                try {
                    $ticket = ORM::factory('ticket')->get_ticket_by_email_and_subject($email, $subject);
                    // вставка
                    if ($isset_re && $ticket->loaded()) {    // ответ
                        $reply = ORM::factory('reply')->add_reply($ticket, $message, $client_name, $email, $date);      
                    } else {            // новый тикет
                        $ticket = ORM::factory('ticket')->add_ticket($mailbox, Model_Ticket::TYPE_EMAIL, $client_name, $email, null, $subject, $message, Model_Ticket::STATUS_ACTIVE, 0, $date);     
                    }
                    
                    // обновление current_mail_id
                    $mailbox->current_mail_id = $id;
                    $mailbox->save();
                } catch (Exception $e) {
                    // TODO разобраться, не должно быть такого
                    if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
                        continue;    
                    }
                }
            }
        }

        // close the connection
        imap_close($inbox);       */
    } catch (Exception $e) {
        //die($e->getMessage());
        //if (strstr($e->getMessage(), 'Unknown: SECURITY PROBLEM: insecure server advertised AUTH=PLAIN') !== false) {
        //    continue;    
        //}
        write_log($mailbox->id." - ".$e->getMessage(), true);
        //file_put_contents(APPPATH.'cronjob/parse_messages_log.txt', date('Y-m-d H:i:s')." - ".$mailbox->id." - ".$e->getMessage()."\r\n", FILE_APPEND);
        //throw $e;   
    }
    
    $mailbox->is_processing = 0;
    $mailbox->save();
} 

function write_log($message, $is_error = false) {
    $type = 'Log';
    if ($is_error) {
        $type = 'Error';  
    }
    file_put_contents(APPPATH.'cronjob/parse_messages_log.txt', date('Y-m-d H:i:s')." - ".$type." - ".$message."\r\n", FILE_APPEND);   
}


/*function get_mime_type(&$structure) { 
    $primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"); 
    if($structure->subtype) { 
        return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype; 
    } 
    return "TEXT/PLAIN"; 
} 

function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) { 

    if (!$structure) { 
        $structure = imap_fetchstructure($stream, $msg_number); 
    } 

    if ($structure) {
        if (!$part_number) { 
            $part_number = "1"; 
        } 
     
        if ($mime_type == get_mime_type($structure)) {            
            $text = imap_fetchbody($stream, $msg_number, $part_number); 
            if (!$text) {
                $text = imap_fetchbody($stream, $msg_number, '2');    
            } 
            if (!$text) {
                $text = imap_fetchbody($stream, $msg_number, '1');    
            } 
            if($structure->encoding == 3) { 
               return imap_base64($text); 
            } else if($structure->encoding == 4) {
               return imap_qprint($text); 
            } else { 
               return $text; 
            } 
        } 
    
        if ($structure->type == 1) { 
            while(list($index, $sub_structure) = each($structure->parts)) { 
                $prefix = ''; 
                if ($part_number) { 
                    if (count(explode('.', $part_number)) > 1) {
                        $prefix = 1 . '.';    
                    } else {
                        $prefix = $part_number . '.'; 
                    }
                }
                $data = get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1)); 
                if ($data) { 
                    return $data; 
                } 
                //$data = get_part($stream, $msg_number, $mime_type, $sub_structure, 1); 
                //if ($data) { 
                //    return $data; 
                //}  
            } // end while 
        } // end multipart 
    } // end structure 
    return false; 
}  */